import { Button } from 'antd';
import React, { Component } from 'react';
import store from '../store'

class ReduxPage extends Component {
  componentDidMount() {
    this.unsubscribe = store.subscribe(() => { // 变更订阅
      this.forceUpdate()
    })
  }
  componentWillUnmount() {
    // 组件卸载之前取消订阅
    if(this.unsubscribe) {
      this.unsubscribe()
    }
  }

  add = () => {
    store.dispatch({type: 'ADD', payload: 100}) // 提交更新dispatch
  }

  asycAdd = () => {
    store.dispatch((dispatch, getState) => {
      setTimeout(() => {
        dispatch({type: 'ADD', payload: 1})
      }, 1000)
    })
  }

  render() {
    return (
      <div>
        <h3>ReduxPage</h3>
        <div>{store.getState()}</div> {/* getState 获取store */}
        <Button onClick={this.add}>add</Button>
        <Button onClick={this.asycAdd}>asyc add</Button>
      </div>
    )
  }
}

export default ReduxPage